<?php
/**
 * Project: AIGC
 * Author: moufer <moufer@163.com>
 * Date: 2024/7/22 00:10
 */

namespace module\ai\library\channel\completion;

use module\ai\library\channel\abstract\Completion;

class AliyunCompletion extends Completion
{
    /**
     * @inheritDoc
     */
    protected function rawToData(): void
    {
        $data = $this->rawData;
        if (isset($data['code'])) {
            if ($data['code'] === 'DataInspectionFailed') {
                $this->error('对不起，我无法回答你的问题。', $data['code'], true);
            } else {
                $this->error($data['message'], $data['code']);
            }
        }
        if (isset($data['output']['choices'][0])) {
            $choice = $data['output']['choices'][0];
            $this->data['message'] = $choice['message'];
            $this->data['status'] = !$this->stream ? 'receiving'
                : (empty($choice['finish_reason']) ? 'receiving' : 'finish');
            $this->data['finish_reason'] = $choice['finish_reason'] ?? ''; //null,stop,length
            $this->data['tokens'] = [
                'send_tokens'    => $data['usage']['input_tokens'] ?? 0,
                'receive_tokens' => $data['usage']['output_tokens'] ?? 0,
                'total_tokens'   => $data['usage']['total_tokens'] ?? 0,
            ];
        }
    }
}